﻿package com.wly.ui
{
	import com.wly.ItemEditerMain;
	import com.wly.data.TypeVO;
	
	import flash.display.Sprite;
	
	public class TypeGrid extends Sprite
	{
		private const TypeCount:int = 25;
		private var _typeAvailable:int = 0;
		
		private var _itemsArr:Array;
		public var itemEditMain:ItemEditerMain;
		
		public function TypeGrid()
		{
			super();
			initChilds();
		}
		
		private function initChilds():void
		{
			var typeItem:TypeItem;
			var i:int;
			
			_itemsArr = [];
			for(i=0; i<TypeCount; i++)
			{
				typeItem = getChildByName("mcItem"+i.toString()) as TypeItem;
				typeItem.index = i;
				typeItem.typeGrid = this;
				typeItem.visible = false;
				_itemsArr.push(typeItem);
			}
		}
		
		private function clear():void
		{
			var typeItem:TypeItem;
			var i:int;
			
			for(i=0; i<TypeCount; i++)
			{
				typeItem = _itemsArr[i] as TypeItem;
				if(typeItem)
				{
					typeItem.setTypeInfo(null);
					typeItem.visible = false;
				}
			}
			_typeAvailable = 0;
		}
		
		private function reset():void
		{			
			var typeItem:TypeItem;
			var i:int;
			
			for(i=0; i<TypeCount; i++)
			{
				typeItem = _itemsArr[i] as TypeItem;
				if(typeItem)
				{
					typeItem.selected = false;
				}
			}
			
		}
		
		public function setTypeItemList(items:Array):void
		{
			var typeItem:TypeItem;
			var typeVo:TypeVO;
			var i:int;
			
			clear();
			_typeAvailable = items.length;
			for(i=0; i<items.length; i++)
			{
				typeVo = items[i] as TypeVO;
				typeItem = _itemsArr[i] as TypeItem;
				if(typeVo && typeItem)
				{
					typeItem.visible = true;
					typeItem.setTypeInfo(typeVo);
				}
			}
		}
		
		public function getSelectedTypes():Array
		{
			var typeItems:Array = [];
			var i:int;
			var typeItem:TypeItem;
			
			for(i=0; i<_typeAvailable; i++)
			{
				typeItem = _itemsArr[i] as TypeItem;
				if(typeItem && typeItem.selected)
				{
					typeItems.push(typeItem.getTypeInfo());
				}
			}
			
			return typeItems;
		}
		
		public function setSelectedTypes(typesid:Array):void
		{
			if(!typesid)
			{
				return;
			}
			
			var typeItem:TypeItem;
			var typeId:int;
			var i:int;
			var j:int;
			
			reset();
			for(i=0; i<_typeAvailable; i++)
			{
				typeItem = _itemsArr[i] as TypeItem;
				for(j=0; j<typesid.length; j++)
				{
					typeId = typesid[j] as int;
					if(typeItem && (typeItem.getTypeInfo().id==typeId))
					{
						typeItem.selected = true;
						break;
					}
				}
			}
		}
		
		public function onTypeSelectChg(index:int):void
		{
			var typeItem:TypeItem = _itemsArr[index] as TypeItem;
			if(itemEditMain && typeItem)
			{
				itemEditMain.updateCurItemType(typeItem.getTypeInfo(), typeItem.selected);
			}
		}
	}
}